//
//  WeatherGetter.m
//  GolfFriend
//
//  Created by Vescky on 13-11-29.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "WeatherGetter.h"
#import "JSON.h"
#import "RegexKitLite.h"
#import "CommonUtility.h"
#import "AppsLocationManager.h"

#define GET_CITYID_API @"http://61.4.185.48:81/g/"
#define GET_WEATHERINFO_API(ID) [NSString stringWithFormat:@"http://m.weather.com.cn/data/%@.html",ID]
#define GET_REALTIME_FORCAST_API(ID) [NSString stringWithFormat:@"http://www.weather.com.cn/data/sk/%@.html",ID]
#define DEFAULT_CITYID @"101280101" //默认广州的

#define BAIDU_WEATHER_FORCAST(lat,lon) [NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=%f,%f&ak=16040cc28c6784d6d17ef30bfd9f31ce&output=json",lon,lat]
//(\u4eca\u5929, \u5b9e\u65f6\uff1a23\u2103)
@implementation WeatherGetter
@synthesize wInfo,delegate;

static WeatherGetter *wGetter;

+ (id)shareWeatherGetter {
    if (!wGetter) {
        wGetter = [[WeatherGetter alloc] init];
    }
    return wGetter;
}

- (WetherInfoVO*)refreshWeather {
    if (!wInfo) {
        wInfo = [[WetherInfoVO alloc] init];
    }
    if (isBusy) {
        return nil;
    }
    isBusy = YES;
//    wInfo.cityId = [self getCityIdViaIP];
//    NSString *allWeatherInfo = [self getSixDaysWeatherInfoWithCityId:wInfo.cityId];
//    NSString *rtWeatherInfo = [self getRealtimeForcastWithCityId:wInfo.cityId];
//    [self parseForWeatherWithSixDaysWeatherString:allWeatherInfo andRealtimeWeatherString:rtWeatherInfo];
    
    NSString *_weatherInfo = [self getBaiduForcast];
    [self parseForBaiduWeatherForcast:_weatherInfo];
    isBusy = NO;
    
    if ([[self delegate] respondsToSelector:@selector(WeatherInfoDidRefreshed)]) {
        [[self delegate] WeatherInfoDidRefreshed];
    }
    
    return wInfo;
}

- (WetherInfoVO*)getWeather {
    WetherInfoVO *wInfo1 = [[WetherInfoVO alloc] init];
    NSUserDefaults *usd = [NSUserDefaults standardUserDefaults];
    NSDictionary *defaultWeatherInfo = [usd objectForKey:@"weatherInfo"];
    [wInfo1 dictionaryToWeatherInfoVO:defaultWeatherInfo];
    return wInfo1;
}

- (bool)isBusy {
    return isBusy;
}

- (void)getWeatherByCityId:(NSString*)cityId {
    
}

//通过当前IP获取城市ID
- (NSString*)getCityIdViaIP {
    NSURL *url = [NSURL URLWithString:GET_CITYID_API];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSArray *arr = [dataString componentsSeparatedByString:@";"];
    for (int i = 0; i < [arr count]; i++) {
        NSString *subStr = [arr objectAtIndex:i];
        NSArray *subArr = [subStr componentsSeparatedByString:@"="];
        if ([subArr count] >= 2) {
            NSString *unitStr = [subArr objectAtIndex:0];
            if ([unitStr isEqualToString:@"var id"]) {
                return [subArr objectAtIndex:1];
            }
        }
    }
    return DEFAULT_CITYID;
}

//(\u4eca\u5929, \u5b9e\u65f6\uff1a23\u2103)
- (NSString*)getBaiduForcast {
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];
    if (!currentLocation) {
        CLLocation *defaultLocation = [[CLLocation alloc] initWithLatitude:23.135727 longitude:113.327367];
        currentLocation = defaultLocation;
    }
//#if DEBUG
//#endif
    NSURL *url = [NSURL URLWithString:BAIDU_WEATHER_FORCAST(currentLocation.coordinate.latitude,currentLocation.coordinate.longitude)];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return dataString;
}

- (bool)parseForBaiduWeatherForcast:(NSString*)wString {
    NSDictionary *dict = [wString JSONValue];
    if (!dict || [dict count] < 1) {
        return NO;
    }
    if (![[dict objectForKey:@"status"] isEqualToString:@"success"]) {
        return NO;
    }
    NSArray *weatherList = [dict objectForKey:@"results"];
    if (!weatherList || [weatherList count] < 1) {
        return NO;
    }
    NSDictionary *detailWeatherInfo = [weatherList objectAtIndex:0];
    if (!detailWeatherInfo) {
        return NO;
    }
    
    wInfo.cityName = [detailWeatherInfo objectForKey:@"currentCity"];
    wInfo.cityNameEn = @"";
    wInfo.cityId = @"";
    NSArray *arr = [detailWeatherInfo objectForKey:@"weather_data"];
    NSMutableArray *tempArr = [[NSMutableArray alloc] init];
    NSMutableArray *weatherArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [arr count]; i++) {
        NSDictionary *dDict = [arr objectAtIndex:i];
        if (i == 0) {
            NSString *currentInfo = [dDict objectForKey:@"date"];
            NSString *currentTmp = [currentInfo stringByMatching:@"：.*℃"];
            currentTmp = [currentTmp stringByReplacingOccurrencesOfString:@"：" withString:@""];
            currentTmp = [currentTmp stringByReplacingOccurrencesOfString:@"℃" withString:@""];
            wInfo.currentTemp = currentTmp;
            wInfo.currentWeather = [dDict objectForKey:@"weather"];
            wInfo.currentWeatherIcon = getWeatherIcon(wInfo.currentWeather, YES);
        }
        
        if ([dDict objectForKey:@"weather"]) {
            NSString *w1 = [dDict objectForKey:@"weather"];
            [weatherArr addObject:[self simplifyWeather:w1]];
        }
        if ([dDict objectForKey:@"temperature"]) {
            NSString *t1 = [dDict objectForKey:@"temperature"];
//            t1 = [t1 stringByReplacingOccurrencesOfRegex:@"\\u*" withString:@""];
            [tempArr addObject:t1];
        }
        
    }
    wInfo.sixDaysTemp = tempArr;
    wInfo.sixDaysWeather = weatherArr;
    return YES;
}


- (NSString*)getSixDaysWeatherInfoWithCityId:(NSString*)cityId {
    if (!cityId || cityId.length < 1) {
        return @"";
    }
    NSURL *url = [NSURL URLWithString:GET_WEATHERINFO_API(cityId)];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return dataString;
}

- (NSString*)getRealtimeForcastWithCityId:(NSString*)cityId {
    if (!cityId || cityId.length < 1) {
        return @"";
    }
    NSURL *url = [NSURL URLWithString:GET_REALTIME_FORCAST_API(cityId)];
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return dataString;
}

- (void)parseForWeatherWithSixDaysWeatherString:(NSString*)sixString andRealtimeWeatherString:(NSString*)rtString {
    NSDictionary *allWeatherInfo = [[sixString JSONValue] objectForKey:@"weatherinfo"];
    NSDictionary *rtWeatherInfo = [[rtString JSONValue] objectForKey:@"weatherinfo"];
    if (!allWeatherInfo || !rtWeatherInfo || !wInfo) {
        return;
    }
    
    //六天的信息
    NSMutableArray *stArr = [[NSMutableArray alloc] init];
    NSMutableArray *swArr = [[NSMutableArray alloc] init];
    for (int i = 1; i <= 6; i++) {
        NSString *tString = [NSString stringWithFormat:@"temp%d",i];
        NSString *wString = [NSString stringWithFormat:@"weather%d",i];
        
        //获取并简化天气
        [swArr addObject:[self simplifyWeather:[allWeatherInfo objectForKey:wString]]];
        
        if ([allWeatherInfo objectForKey:tString]) {
            [stArr addObject:[allWeatherInfo objectForKey:tString]];
        }
        else {
            [stArr addObject:@"0"];
        }
    }
    
    wInfo.sixDaysTemp = stArr;
    wInfo.sixDaysWeather = swArr;
    
    //实时温度
    if ([rtWeatherInfo objectForKey:@"temp"]) {
        wInfo.currentTemp = [rtWeatherInfo objectForKey:@"temp"];
    }
    else {
        wInfo.currentTemp = @"0";
    }
    
    wInfo.currentWeather = [wInfo.sixDaysWeather objectAtIndex:0];
    
    wInfo.currentWeatherIcon = getWeatherIcon(wInfo.currentWeather,YES);//[self getWeatherIcon:wInfo.currentWeather];
    
    wInfo.cityName = [allWeatherInfo objectForKey:@"city"];
    wInfo.cityNameEn = [allWeatherInfo objectForKey:@"city_en"];
}

//把天气简化成四种：晴、雨、雪、阴 
- (NSString*)simplifyWeather:(NSString*)w {
    if (!w || w.length < 1) {
        return @"晴";
    }
    NSString *str = @"";
    if ([w stringByMatching:@"晴"]) {
        str = @"晴";
    }
    else if ([w stringByMatching:@"雨"]) {
        str = @"雨";
    }
    else if ([w stringByMatching:@"雪"]) {
        str = @"雪";
    }
    else {
        //阴天，包括多云，沙尘暴，灰霾等等
        str = @"阴";
    }
    return str;
}




@end
